package com.getsendsocial.GetSendSocial.Database;

import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import com.getsendsocial.GetSendSocial.Model.FraseModel;
import com.getsendsocial.GetSendSocial.Model.FraseToPostModel;
import com.getsendsocial.GetSendSocial.Model.FraseToPostModelResponse;
import com.getsendsocial.GetSendSocial.Util.AddTab;

public class PostString extends AsyncTask<FraseToPostModel, Void, FraseModel> {
	
	private Context context;
	public static int flag;
	private GSDatabase db;

	public PostString(Context c){
		context = c;
	}    		

	@Override
	protected void onPostExecute(FraseModel fraseModel){
		super.onPostExecute(fraseModel);
		
		if(fraseModel==null){
			return;
		}else{
			db = new GSDatabase(context);
	       	db.open();
	       	String resp = db.insertFrase(fraseModel);
	       	db.close();
	       	if(resp.equals("SUCCESS")){
	           	Toast.makeText(context,"La tua frase è stata postata sul server ed inserita nel tuo database!", Toast.LENGTH_LONG).show();
	       	}else{
	           	Toast.makeText(context,"Si è verificato un errore nel salvataggio della frase. Riprova!", Toast.LENGTH_LONG).show();
	       	}
	       	AddTab.pdialog.dismiss();
		}
	}
	
	@Override
	protected FraseModel doInBackground(FraseToPostModel... obj) {
		
		String url = "http://getsenddev.appspot.com/postFrase";
		// Set the Content-Type header
		RestTemplate restTemplate = new RestTemplate();
		restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
		FraseToPostModelResponse[] responseEntity = null;
		try{
			responseEntity = restTemplate.postForObject(url,obj[0], FraseToPostModelResponse[].class);
			FraseModel frase = new FraseModel();
			frase.setId(responseEntity[0].getId());
			frase.setText(obj[0].getText());
			frase.setType(obj[0].getType());
			return frase;
		}catch(RestClientException rce){
	       	Toast.makeText(context,"Si è verificato un errore durante la comunicazione col server. Riprova!", Toast.LENGTH_LONG).show();
	       	return null;
		}
		
		}
}
